package com.platform.common.core.utils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.platform.common.core.utils.sql.SqlUtil;
import com.platform.common.core.web.page.PageDomain;
import com.platform.common.core.web.page.TableSupport;

import java.util.List;

/**
 * 分页工具类
 *
 * @author
 */
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }


    /**
     * 分页结果处理
     *
     * @param oldData 旧数据
     * @param newData 新数据
     * @param <T>     旧数据类型
     * @param <K>     新数据类型
     * @return 新数据
     */
    public static <T, K> List<T> convertResult(List<K> oldData, List<T> newData) {
        if (newData instanceof Page) {
            return newData;
        } else if (oldData instanceof Page) {
            Page<K> oldPage = (Page<K>) oldData;
            Page<T> page = new Page<>();
            page.addAll(newData);
            page.setPageNum(oldPage.getPageNum());
            page.setPageSize(oldPage.getPageSize());
            page.setTotal(oldPage.getTotal());
            return page;
        } else {
            return newData;
        }
    }
}
